const express = require('express');
const process = require('child_process');
const bodyParser = require('body-parser');
const app = express();

const { pull_request: {
  hook_name,
  app: appList,
}} = require('./config.json');


app.use(express.json());
app.use(bodyParser.json({ limit: '102400kb' }))
app.use(bodyParser.urlencoded({
  extended: true,
}));

app.use(express.urlencoded({ extended: false }));

app.post('/', function (req) {
  if (
    req
    && req.body
    && req.body.hook_name === hook_name
  ) {
    console.log(req.body.password);
    appList.forEach(({ password, branch, merged, state, cmd}) => {
      if (
          req.body.password === password
          && req.body.pull_request
          && req.body.pull_request.base.ref === branch
          && req.body.pull_request.merged === merged
          && req.body.pull_request.state === state
      ) {
        cmd.forEach(function (c) {
          process.exec(c, function (err, stdout, stderr) {
            if (err) {
              console.log('err', err);
            }
            console.log('stdout: \n' + stdout + '\n');
            console.error('stderr: \n' + stderr + '\n');
          });
        });
      }
    });
  } else {
    console.log('not standard pull request');
  }
});

app.listen(9277, () => {
  console.log('server stared..');
});
